//
//  NewApiClient.swift
//  souyun
//
//  Created by SkyGrass on 16/5/29.
//  Copyright © 2016年 SkyGrass. All rights reserved.
//

import Foundation

class NewApiClient: ApiServiceProtocol {
    func search(_request: request, _searchword: String, _pageindex: Int, _completionHandler: completionHandler) {
        _request.post(["q":_searchword,"page":_pageindex], callback:{
            data in
            var returnviewdata = [ViewData]()
            if NSJSONSerialization.isValidJSONObject(data){
                let showapi_res_code = data.objectForKey("showapi_res_code")as? Int
                let showapi_res_error = data.objectForKey("showapi_res_error")as? String
                
                if showapi_res_code! == 0{
                    if let contentArray : NSArray = data.objectForKey("showapi_res_body")!.objectForKey("pagebean")!.objectForKey("contentlist") as? NSArray{
                        if  contentArray.count <= 0 {
                            _completionHandler(nil,Error(_code:-1,_errMsg: "No data found"))
                        }else{
                            for item in contentArray{
                                let _viewdata = ViewData()
                                _viewdata.content = item.objectForKey("content")! as? String
                                _viewdata.url = item.objectForKey("url")! as? String
                                _viewdata.title = item.objectForKey("title")! as? String
                                returnviewdata.append(_viewdata)
                            }
                            _completionHandler(returnviewdata,Error(_code:0,_errMsg: "ok"))
                        }
                    }
                }else{
                    _completionHandler(nil ,Error(_code:-1,_errMsg:showapi_res_error!))
                }
            }
            else{
                _completionHandler(nil ,Error(_code:-1,_errMsg:"Not Json"))
            }
        })
    }
}
